<?php

namespace App\Repositories;

use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use App\Models\Shop;
use App\Models\ShopDish;
use App\Models\ShopMenu;
use App\Models\ShopRoomTable;
use App\Models\OrderScan;
use App\Models\ShopDishAttribute;
use App\Models\Order;
use App\Tools\Activity;

class ScanRepository
{
    //获取桌子信息
    public function getOne($id){
        //根据获取id获取房桌
        if(!$id){
            return show(30001,"传入参数有误");
        }
        $room_desk = ShopRoomTable::find($id,['name','type','lock_qrcode','shop_id','note','thumb']);
        if(!$room_desk){
            return show(30001,"房间或桌子不存在");
        }else{
            if($room_desk->lock_qrcode!=1){
                return show(30001,"该房间未启用二维码");
            }
            //获取商铺信息
            $shop =Shop::where('is_check',1)->find($room_desk->shop_id,['id','shop_name','shop_avatar','shop_pic','note']);
            if(!$shop){
                return show(30001,"商家不存在");
            }
            $menu = ShopMenu::where('shop_id',$room_desk->shop_id)->orderBy('menu_sort','ASC')->get(['id', 'menu_name'])->toArray();
            //处理空菜单
            foreach($menu as $k=>$v){
                $checkdish = ShopDish::where('menu_id',$v['id'])->where('status',1)->first();
                if(!$checkdish){
                    unset($menu[$k]);
                }
            }
            $shop->nowdeskroom = $room_desk;
            $shop->shopmenu = array_merge($menu);
            return show(200,"获取信息成功",$shop);
        }
    }

    //确定下单
    public function addOrder($cart,$sightseer){
//        $cart = [
//            "shop_id"=>1,     //店铺id
//            "room_desk_id"=>1,//房桌id
//            "number"=>3,      //商品数量
//            "top_price"=>21.8,//商品总价
//            "dish"=>[//菜单
//                [ //多规格情况
//                    'dishes_id' =>1,
//                    'dishes_name'=>'催情肉卷',
//                    'goods_number'=>2,
//                    'price'=>5.00,     //数据单价
//                    'sell_price'=>5.00,//实际单价（计算后）
//                    'is_attr'=>1,
//                    'spec'=>"甜|0,大份|5",
//                ],
//                [ //非多规格情况
//                    'dishes_id' =>2,
//                    'dishes_name'=>'贤威炒蛋',
//                    'goods_number'=>2,
//                    'price'=>5.00,
//                    'sell_price'=>5.00,//实际单价（计算后）
//                    'is_attr'=>0,
//                    'spec'=>'',
//                ],
//            ]
//        ];
        //获取当前
        if(Auth::id()){
            $user_id=Auth::id();
        }else{
            $user_id=-1;
        }
        //验证购物车
        if(empty($cart) || empty($cart['dish'])){
            return show("30003","购物车不存在！");
        }
        //验证商家
        $shop = Shop::find($cart["shop_id"]);
        if(!$shop){
            return show("30001","店铺不存在或未审核！");
        }
        //店铺休息
        if($shop->shopinfo->is_open==0){
            return show("30001","店铺休息中！");
        }
        //营业时间
        $opentimes = explode(',',$shop->shopinfo->opentime);
        $check_time =0;
        foreach($opentimes as $k=>$v){
            $opentime =explode('--',$v);
            if(strtotime($opentime[0])<=time() && strtotime($opentime[1])-900>=time()){
                $check_time +=1;
            }else{
                $check_time +=0;
            }
        }
        if($check_time==0){
            return show("30001","店铺休息中");
        }
        //验证价格(除非你有更好的方法否则别乱来)
        $top_amount=$top_price = 0;
        foreach($cart['dish'] as $k=>$v)
        {
            $dishes = ShopDish::find($v['dishes_id']);
            if($dishes) {
                $dishes = $dishes->toArray();
                if ($dishes['is_attr'] == 1) {
                    //获取数据库的规格计算
                    $ShopDishAttribute = ShopDishAttribute::where('dish_id', $dishes['id'])->get();
                    $spec_price = 0;
                    foreach ($ShopDishAttribute as $k2 => $v2) {
                        foreach (explode(',', $v2['spec']) as $k3 => $v3) {
                            $spec = explode('|', $v3);
                            //获取购物车的规格计算
                            $cart_dish_spec = explode(',', $cart['dish'][$k]['spec']);
                            foreach ($cart_dish_spec as $k4 => $v4) {
                                $cart_spec = explode('|', $v4);
                                if ($cart_spec[0] == $spec[0]) {
                                    $spec_price += floatval($spec[1]);
                                }
                            }
                        }
                    }
                    //（规格价+基础价）* 数量 * 折扣
                    $top_amount += ($spec_price + $dishes['price']) * $cart['dish'][$k]['goods_number'] * $dishes['discount'];
                    $top_price  += ($spec_price + $dishes['price']) * $cart['dish'][$k]['goods_number'];
                } else {
                    $top_amount += $dishes['price'] * $cart['dish'][$k]['goods_number'] * $dishes['discount'];
                    $top_price  += $dishes['price'] * $cart['dish'][$k]['goods_number'];
                }
            }
        }

        //强转防止溢出
        $top_amount = round($top_amount,2);
        if($top_amount!=$cart['top_price']){
            return show("30003","购物车异常！",["top_price" => $top_amount]);
        }
//        if($top_amount<$shop->shopinfo->min_spend){
//            return show("30003","未达起送价！");
//        }
        //验证房桌桌子
        //return $cart['room_desk_id'];
        $room_desk = ShopRoomTable::find($cart['room_desk_id']);
        if(!$room_desk){
            return show("30004","房间或桌子不存在！");
        }
        if($room_desk->shop_id != $cart['shop_id']){
            return show("30004","房间或桌子不存在");
        }
        //生成订单
        $insert=Order::create([
              "user_id"=>$user_id,        //用户id
              "shop_id"=>$cart["shop_id"],//商铺id
              "order_type"=>3,            //扫码
              "order_number"=>randID(),   //订单编号
              "order_status"=>1,          //订单状态
              "order_price"=>$top_amount, //订单总价
              "note"=>$cart["note"],      //订单备注
              "order_amount"=>$top_amount,//实际价格
              "product_type"=>1,          //餐饮模块（1）
        ]);
        //生成详细
        OrderScan::create([
            "order_id"=>$insert['id'],     //订单id
            "room_desk_id"=>$room_desk->id,//
            "desk_name"=>$room_desk->name, //餐饮模块（1）
        ]);
        //处理详情
        foreach($cart['dish'] as $k=>$v){
            $cart['dish'][$k]['order_id']=$insert['id'];
            $cart['dish'][$k]['amount']  = $v['goods_number']*$v['sell_price'];
        }
        DB::table('order_details')->insert($cart["dish"]);
        //单单立减
        $activity = new Activity();
        $activity->activity($insert['id'],1);
        return show("200","下单成功",["order_id"=>$insert['id'],"money"=>$top_amount,"order_type"=>3]);
    }


    //加菜
    public function addDishes($cart){//暂不使用
        return;
        //验证用户
        if(!Auth::id()){
            return show(30001,'请先登录');
        }
        //验证购物车
//        $cart = [
//            "order_id"=>5,
//            "dish"=>[//菜单
//                [ //多规格情况
//                    'dishes_id' =>1,
//                    'dishes_name'=>'催情肉卷',
//                    'goods_number'=>2,
//                    'price'=>5.00,
//                    'sell_price'=>5.00,
//                    'is_attr'=>1,
//                    'spec'=>"甜|0,大份|5",
//                ],
//                [ //非多规格情况
//
//                    'dishes_id' =>2,
//                    'dishes_name'=>'贤威炒蛋',
//                    'goods_number'=>2,
//                    'price'=>5.00,
//                    'sell_price'=>5.00,
//                    'is_attr'=>0,
//                    'spec'=>'',
//                ],
//            ]
//        ];

        $order = Order::where('order_type',1)->find($cart['order_id']);
        if(!$order){
            return show(30001,'订单验证错误，订单不存在');
        }else{
            if(Auth::id() != $order->user_id){
                return show(30001,'没权限！');
            }
            if($order->order_status != 3){
                return show(30001,"当前订单状态不可加菜");
            }
            //计算价格
            $top_amount=$top_price = 0;
            foreach($cart['dish'] as $k=>$v)
            {
                $dishes = ShopDish::find($v['dishes_id'])->toArray();
                if($dishes['is_attr']==1){
                    //获取数据库的规格计算
                    $ShopDishAttribute = ShopDishAttribute::where('dish_id',$dishes['id'])->get();
                    $spec_price = 0;
                    foreach($ShopDishAttribute as $k2=>$v2)
                    {
                        foreach(explode(',',$v2['spec']) as $k3=>$v3)
                        {
                            $spec = explode('|',$v3);
                            //获取购物车的规格计算
                            $cart_dish_spec = explode(',',$cart['dish'][$k]['spec']);
                            foreach($cart_dish_spec as $k4=>$v4){
                                $cart_spec = explode('|',$v4);
                                if($cart_spec[0]==$spec[0]){
                                    $spec_price += floatval($spec[1]);
                                }
                            }
                        }
                    }
                    //（规格价+基础价）* 数量 * 折扣
                    $top_amount += ($spec_price+$dishes['price'])*$cart['dish'][$k]['goods_number']*$dishes['discount'];
                    $top_price  += ($spec_price+$dishes['price'])*$cart['dish'][$k]['goods_number'];
                }else{
                    $top_amount += $dishes['price'] * $cart['dish'][$k]['goods_number']*$dishes['discount'];
                    $top_price  += $dishes['price'] * $cart['dish'][$k]['goods_number'];
                }

            }
            //强转防止溢出
            $top_amount = round($top_amount,2);
            //更新订单
            $order->order_price = $order->order_price+$top_amount;
            $order->save();
            //添加菜式到订单
            foreach($cart['dish'] as $k=>$v){
                $cart['dish'][$k]['order_id']=$cart['order_id'];
                $cart['dish'][$k]['amount']  = $v['goods_number']*$v['sell_price'];
            }
            DB::table('order_details')->insert($cart["dish"]);
            return show(200,'加菜成功');
        }
    }

    //呼叫服务员
    public function callAttendant($id){
        //验证用户
        if(!Auth::id()){
            return show(30001,'请先登录');
        }
        $order = Order::where('order_type',3)->where('order_status',4)->find($id);
        if(!$order){
            return show(30001,'订单验证错误，不允许呼叫');
        }else{
            if(Auth::id() != $order->user_id){
                return show(30001,'没权限！');
            }
            //return $order->created_at;
            if(strtotime($order->created_at)+$order->shopinfo->eating_time*3600<time()){
                return  show(30001,'已超过可呼叫时间');
            }
            //通知服务员
            return show('200','呼叫成功，请耐心等待');
        }
    }

}
